﻿using JinYuan.Helper;
using JinYuan.MES.Enums;
using JinYuan.Models;
using JinYuan.VirtualDataLibrary;
using Language;
using MiniExcelLibs;
using PLCCommunication.Common.DataConvert;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace LargeSquareOne
{
    public partial class FrmHistory : MultiLanguageForm
    {
        public static FrmHistory _Form;// 单例模式

        public FrmHistory()
        {
            InitializeComponent();

            //this.cmb_SelectType.Items.Add("进站".Translated());
            //this.cmb_SelectType.Items.Add("出站".Translated());
            ////this.cmb_SelectType.Items.Add("结构件料盘".Translated());
            //this.cmb_SelectType.Items.Add("进站失败".Translated());
            //this.cmb_SelectType.Items.Add("出站失败".Translated());
            this.cmb_SelectType.Items.AddRange(new string[] { "进站".Translated(), "出站".Translated(), "进站失败".Translated(), "出站失败".Translated() });
            this.cmb_SelectType.SelectedIndex = 0;

            this.dtp_Start.Value = DateTime.Now.AddHours(-2.0f);
            this.dtp_End.Value = DateTime.Now;

            this.cmb_AlarmType.Items.AddRange(new string[] { "全天".Translated(), "白班".Translated(), "夜班".Translated() });
            this.cmb_AlarmType.SelectedIndex = 0;

            this.cmbClass.Items.AddRange(new string[] { "白班".Translated(), "夜班".Translated() });
            this.cmbClass.SelectedIndex = 0;

            _Form = this;
        }




        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Query_Click(object sender, EventArgs e)
        {
            string str = this.cmb_SelectType.Text;
            if (string.Compare(str, "进站".Translated()) == 0)
            {
                this.cmb_SelectType.SelectedIndex = 0;
            }
            else if (string.Compare(str, "出站".Translated()) == 0)
            {
                this.cmb_SelectType.SelectedIndex = 1;
            }
            string rfid = this.txtBarCodeORRfid.Text.Trim();
            string barCode = this.txtSteelShellCode.Text.Trim();
            string start = this.dtp_Start.Text;
            string end = this.dtp_End.Text;
            int selectType = this.cmb_SelectType.SelectedIndex;

            Task<DataResult<DataTable>> task1 = Task.Run(() =>
            {
                return QueryProcess(selectType, rfid, barCode, start, end);

            });

            var task2 = task1.ContinueWith(task =>
            {
                this.Invoke(new Action(() =>
                {
                    if (task.Result.IsSuccess)
                    {

                        this.dgv_Main.DataSource = null;

                        this.dgv_Main.DataSource = task.Result.Content;
                    }
                    else
                    {
                        new FrmMsgBoxOutWithAck(2, "查询失败：".Translated() + task.Result.Message, "错误提示".Translated()).Show();
                    }
                }));
            });
        }

        public List<BGearEntity> queryProcessListB;
        public List<AGearEntity> queryProcessListA;
        /// <summary>
        /// DataTable-->List
        /// 获取三语切换的DataTable.ColumnName
        /// </summary>
        /// <param name="selectType"></param>
        /// <param name="dataTable"></param>
        /// <returns></returns>
        public DataTable GetHistoryOutData(int selectType, DataTable dataTable)
        {
            string selectTypeStr = "";
            //出站数据保存成List
            switch (selectType)
            {
                case 0:
                case 2:
                    queryProcessListA = dataTable.ToList<AGearEntity>();
                    selectTypeStr = "FrmHistory_dgv_Main_";
                    break;
                case 1:
                case 3:
                    queryProcessListB = dataTable.ToList<BGearEntity>();
                    selectTypeStr = "FrmHistory_dgv_Main_";
                    break;
                case 4:
                    selectTypeStr = "FrmHistory_dgvClass_";
                    break;
                case 5:
                    selectTypeStr = "FrmHistory_dgvDays_";
                    break;
                case 6:
                    selectTypeStr = "FrmHistory_dgvMonth_";
                    break;
                case 7:
                    selectTypeStr = "FrmHistory_dgvWeek_";
                    break;
                case 8:
                    selectTypeStr = "FrmHistory_dgv_AlarmData_";
                    break;
            }

            // 自定义获取新列名的方法 钩子函数
            Func<string, string> GetNewColumnName = originalName =>
            {
                // 这里可以根据具体需求实现自定义逻辑
                return LanguageManager.GetString($"{selectTypeStr + originalName}"); ;
            };

            // 使用自定义方法替换列名
            dataTable = dataTable.ReplaceColumnNamesWithCustomMethod(GetNewColumnName);

            return dataTable;
        }

        private PLCCommunication.Common.DataConvert.DataResult<DataTable> QueryProcess(int selectType, string rfid, string barCode, string start, string end)
        {
            //判断时间
            DateTime startTime = Convert.ToDateTime(start);
            DateTime endTime = Convert.ToDateTime(end);
            if (startTime > endTime)
            {
                return DataResult.CreateFailResult<DataTable>("开始时间不能大于结束时间".Translated());
            }
            TimeSpan timeSpan = endTime - startTime;
            if (timeSpan.TotalDays > 7.0)
            {
                return DataResult.CreateFailResult<DataTable>("查询时间不能超过7天".Translated());
            }

            DataTable dataTable = CommonMethods.db.QueryDataTable(CommonMethods.dBSQL.SelectHostData(selectType, rfid, barCode, start, end));
            if (dataTable != null)
            {
                dataTable = GetHistoryOutData(selectType, dataTable);
                return DataResult.CreateSuccessResult<DataTable>(dataTable);
            }
            else
            {
                return DataResult.CreateFailResult<DataTable>("未能查到数据，请检测".Translated());
            }
        }

        private void btn_ExPort_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();

            saveFileDialog.Filter = "XLSX文件(*.xlsx)|*.xlsx|所有文件|*.*";
            saveFileDialog.Title = "导出历史数据";
            saveFileDialog.FileName = "历史数据".Translated() + DateTime.Now.ToString("yyyyMMddHHmmss");
            saveFileDialog.DefaultExt = "xlsx";
            saveFileDialog.AddExtension = true;

            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {

                MiniExcel.SaveAs(saveFileDialog.FileName, this.dgv_Main.DataSource);

                if (new FrmMsgBoxWithAck("导出报表成功，是否立即打开？".Translated(), "打开报表记录".Translated()).ShowDialog() == DialogResult.OK)
                {
                    Process.Start(saveFileDialog.FileName);
                }
                else
                {
                    new FrmMsgBoxOutWithAck(2, "导出报表失败".Translated(), "数据报表导出".Translated()).ShowDialog();
                }
            }
        }


        /// <summary>
        /// 显示序列号
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgv_Main_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            DataGridViewHelper.DgvRowPostPaint((DataGridView)sender, e);
        }

        /// <summary>
        /// 给DataGridView绘制边框
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgv_Main_Paint(object sender, PaintEventArgs e)
        {
            DataGridViewHelper.DgvRowPaint((DataGridView)sender, e, Color.FromArgb(1, 146, 235));
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgv_Main_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (e.RowIndex != -1 && e.ColumnIndex >= 5)
            {
                object value = this.dgv_Main.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;

                if (value == null || value?.ToString().Length == 0)
                {
                    e.Value = "--";
                }
            }
        }

        #region 减少闪烁
        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams parss = base.CreateParams;
                parss.ExStyle |= 0x02000000;
                return parss;
            }
        }
        #endregion



        #region 统计查询
        /// <summary>
        /// 班次
        /// </summary>
        private DataTable dtClasses = null;
        /// <summary>
        /// 日
        /// </summary>
        private DataTable dtDays = null;
        /// <summary>
        /// 周
        /// </summary>
        private DataTable dtWeeks = null;
        /// <summary>
        /// 月
        /// </summary>
        private DataTable dtMonths = null;

        #region 1、按班次查询
        /// <summary>
        /// 按班次查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_ClassQuery_Click(object sender, EventArgs e)
        {
            dtClasses = null;
            DateTime strDate = dtClass.Value;
            int strClass = cmbClass.SelectedIndex;
            dtClasses = CommonMethods.db.QueryDataTable(CommonMethods.dBSQL.GetStaticByShift(strDate, strClass, CommonMethods.ChangeClassTime));
            //if (dtClasses != null)//&& dtClasses.Rows.Count > 0
            //{
            //    this.dgvClass.DataSource = null;
            //    this.dgvClass.DataSource = dtClasses;
            //}

            if (dtClasses != null)
            {
                dtClasses = GetHistoryOutData(4, dtClasses);
                this.dgvClass.DataSource = null;
                this.dgvClass.DataSource = dtClasses;
            }
        }

        /// <summary>
        /// 按班次导出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_ClassExPort_Click(object sender, EventArgs e)
        {
            if (dgvClass.Columns.Count <= 0)
            {
                MessageBox.Show("导出失败，无查询结果");
                return;
            }

            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.FileName = $"产能统计_按班次统计_{DateTime.Now.ToString("yyyyMMddHHmmss")}";
            saveFileDialog.Filter = "*|*.csv";
            if (saveFileDialog.ShowDialog() == DialogResult.Cancel)
                return;

            string msg = "";
            if (CSVHelper<object>.ExportDataTableToCSV(dtClasses, saveFileDialog.FileName, out msg))
            {
                MessageBox.Show("导出成功!");
            }
        }
        #endregion

        # region 2、按日查询

        /// <summary>
        /// 按日查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_DaysQuery_Click(object sender, EventArgs e)
        {
            dtDays = null;
            string startDateTime = dtpDays.Value.ToString("yyyy-MM-dd 00:00:00");
            string endDateTime = dtpDays.Value.ToString("yyyy-MM-dd 23:59:59");
            dtDays = CommonMethods.db.QueryDataTable(CommonMethods.dBSQL.GetStaticByDay(startDateTime, endDateTime));
            //if (dtDays != null )//&& dtDays.Rows.Count > 0
            //{
            //    this.dgvDays.DataSource = null;
            //    this.dgvDays.DataSource = dtDays;
            //}
            if (dtDays != null)
            {
                dtDays = GetHistoryOutData(5, dtDays);
                this.dgvDays.DataSource = null;
                this.dgvDays.DataSource = dtDays;
            }
        }

        /// <summary>
        /// 按日导出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_DaysExPort_Click(object sender, EventArgs e)
        {
            if (dgvDays.Columns.Count <= 0)
            {
                MessageBox.Show("导出失败，无查询结果");
                return;
            }

            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.FileName = $"产能统计_按日统计_{DateTime.Now.ToString("yyyyMMddHHmmss")}";
            saveFileDialog.Filter = "*|*.csv";
            if (saveFileDialog.ShowDialog() == DialogResult.Cancel)
                return;

            string msg = "";
            if (CSVHelper<object>.ExportDataTableToCSV(dtDays, saveFileDialog.FileName, out msg))
            {
                MessageBox.Show("导出成功!");
            }
        }

        #endregion

        #region 3、按周查询
        /// <summary>
        /// 按周查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_WeekQuery_Click(object sender, EventArgs e)
        {
            dtWeeks = null;
            //确定星期几
            var index = (int)dtpWeek.Value.DayOfWeek;
            index = index == 0 ? 7 : index;
            //当前周的范围
            string retStartDay = dtpWeek.Value.AddDays(-(index - 1)).ToString();
            string retEndDay = dtpWeek.Value.AddDays(7 - index).ToString();

            dtWeeks = CommonMethods.db.QueryDataTable(CommonMethods.dBSQL.GetStaticByWeek(retStartDay, retEndDay));
            //if (dtWeeks != null)//&& dtWeeks.Rows.Count > 0
            //{
            //    this.dgvWeek.DataSource = null;
            //    this.dgvWeek.DataSource = dtWeeks;
            //}
            if (dtWeeks != null)
            {
                dtWeeks = GetHistoryOutData(7, dtWeeks);
                this.dgvWeek.DataSource = null;
                this.dgvWeek.DataSource = dtWeeks;
            }
        }

        /// <summary>
        /// 按周导出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_WeekExPort_Click(object sender, EventArgs e)
        {
            if (dgvWeek.Columns.Count <= 0)
            {
                MessageBox.Show("导出失败，无查询结果");
                return;
            }

            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.FileName = $"产能统计_按周统计_{DateTime.Now.ToString("yyyyMMddHHmmss")}";
            saveFileDialog.Filter = "*|*.csv";
            if (saveFileDialog.ShowDialog() == DialogResult.Cancel)
                return;

            string msg = "";
            if (CSVHelper<object>.ExportDataTableToCSV(dtWeeks, saveFileDialog.FileName, out msg))
            {
                MessageBox.Show("导出成功!");
            }
        }
        #endregion

        #region 4、按月查询
        /// <summary>
        /// 按月查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_MonthQuery_Click(object sender, EventArgs e)
        {

            dtMonths = null;
            string startDateTime = dtMonth.Value.ToString("yyyy-MM-01 00:00:00");

            string endDateTime = new DateTime(dtMonth.Value.Year, dtMonth.Value.Month, DateTime.DaysInMonth(dtMonth.Value.Year, dtMonth.Value.Month)).ToString("yyyy-MM-dd 23:59:59");//通过指定日期计算当月最后一天
            dtMonths = CommonMethods.db.QueryDataTable(CommonMethods.dBSQL.GetStaticByMonth(startDateTime, endDateTime));
            //if (dtMonths != null)// && dtMonths.Rows.Count > 0
            //{
            //    this.dgvMonth.DataSource = null;
            //    this.dgvMonth.DataSource = dtMonths;
            //}
            if (dtMonths != null)
            {
                dtMonths = GetHistoryOutData(6, dtMonths);
                this.dgvMonth.DataSource = null;
                this.dgvMonth.DataSource = dtMonths;
            }
        }

        /// <summary>
        /// 按月导出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_MonthExPort_Click(object sender, EventArgs e)
        {
            if (dgvMonth.Columns.Count <= 0)
            {
                MessageBox.Show("导出失败，无查询结果");
                return;
            }

            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.FileName = $"产能统计_按月统计_{DateTime.Now.ToString("yyyyMMddHHmmss")}";
            saveFileDialog.Filter = "*|*.csv";
            if (saveFileDialog.ShowDialog() == DialogResult.Cancel)
                return;

            string msg = "";
            if (CSVHelper<object>.ExportDataTableToCSV(dtMonths, saveFileDialog.FileName, out msg))
            {
                MessageBox.Show("导出成功!");
            }
        }

        #endregion

        #endregion


        /// <summary>
        /// 选择班次时间变更
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cmb_AlarmType_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmb_AlarmType.SelectedIndex == 1) //白班
            {
                DateTime baiClassStart = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd 8:30:00"));
                DateTime baiClassEnd = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd 20:29:59"));

                dtp_AlarmTimeStart.Value = baiClassStart;
                dtp_AlarmTimeEnd.Value = baiClassEnd;
            }
            else if (cmb_AlarmType.SelectedIndex == 2) //夜班
            {
                DateTime yeClassStart = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd 20:30:00"));
                DateTime yeClassEnd = Convert.ToDateTime(DateTime.Now.AddDays(1).ToString("yyyy-MM-dd 8:29:59"));

                dtp_AlarmTimeStart.Value = yeClassStart;
                dtp_AlarmTimeEnd.Value = yeClassEnd;
            }
            else
            {
                DateTime baiClassStart = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd 00:00:00"));
                DateTime baiClassEnd = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd 23:59:59"));

                dtp_AlarmTimeStart.Value = baiClassStart;
                dtp_AlarmTimeEnd.Value = baiClassEnd;
            }
        }

        #region 报警查询
        /// <summary>
        /// 查询数据
        /// </summary>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <param name="alarmType"></param>
        /// <returns></returns>
        private DataResult<DataTable> QueryProcess(string start, string end, int alarmType)
        {
            DateTime startDateTime = Convert.ToDateTime(start);
            DateTime endDateTime = Convert.ToDateTime(end);

            if (startDateTime >= endDateTime)
            {
                return DataResult.CreateFailResult<DataTable>("开始时间不能大于结束时间".Translated());
            }

            TimeSpan timeSpan = endDateTime - startDateTime;

            if (timeSpan.TotalDays > 1.0)
            {
                return DataResult.CreateFailResult<DataTable>("查询范围不能超过1天".Translated());
            }

            DataTable dataTable = CommonMethods.db.QueryDataTable(CommonMethods.dBSQL.SelectHostAlarmData(start, end, alarmType));
            if (dataTable != null)
            {
                dataTable = GetHistoryOutData(8, dataTable);
                return DataResult.CreateSuccessResult<DataTable>(dataTable);
            }
            else
            {
                return DataResult.CreateFailResult<DataTable>("未能查到数据，请检测".Translated());
            }
        }


        /// <summary>
        /// 报警信息查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_AlarmQuery_Click(object sender, EventArgs e)
        {
            string start = this.dtp_AlarmTimeStart.Text;
            string end = this.dtp_AlarmTimeEnd.Text;

            int alarmType = this.cmb_AlarmType.SelectedIndex;

            Task<DataResult<DataTable>> task1 = Task.Run(() =>
            {
                return QueryProcess(start, end, alarmType);
            });

            var task2 = task1.ContinueWith(task =>
            {
                this.Invoke(new Action(() =>
                {
                    if (task.Result.IsSuccess)
                    {
                        this.dgv_AlarmData.DataSource = null;
                        this.dgv_AlarmData.DataSource = task.Result.Content;
                    }
                    else
                    {
                        new FrmMsgBoxOutWithAck(2, "查询失败：".Translated() + task.Result.Message, "报警查询".Translated()).Show();
                    }
                }));
            });
        }


        /// <summary>
        /// 报警信息导出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_AlarmExport_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "XLSX文件(*.xlsx)|*.xlsx|所有文件|*.*";
            saveFileDialog.Title = "导出历史报警";
            saveFileDialog.FileName = "历史报警".Translated() + DateTime.Now.ToString("yyyyMMddHHmmss");
            saveFileDialog.DefaultExt = "xlsx";
            saveFileDialog.AddExtension = true;

            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                MiniExcel.SaveAs(saveFileDialog.FileName, this.dgv_AlarmData.DataSource);

                if (new FrmMsgBoxWithAck("导出报警成功，是否立即打开？".Translated(), "打开报警记录".Translated()).ShowDialog() == DialogResult.OK)
                {
                    Process.Start(saveFileDialog.FileName);
                }
            }
        }

        private void dgv_AlarmData_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            DataGridViewHelper.DgvRowPostPaint((DataGridView)sender, e);
        }
        #endregion

        #region 进出站补传Mes
        /// <summary>
        /// 进出站补传Mes
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void btn_ReUpMes_Click(object sender, EventArgs e)
        {
            this.btn_ReUpMes.Text = "补传中……".Translated();
            this.btn_ReUpMes.Enabled = false;
            #region
            int selectType = this.cmb_SelectType.SelectedIndex;
            List<string> barCodes = new List<string>();
            string remark = string.Empty;
            MesResType mesResType = MesResType.D;
            string flag = "2";
            string result = string.Empty;
            string info = string.Empty;
            bool totalUpResult = false;

            //0、拿到数据源
            DataTable dt = (DataTable)this.dgv_Main.DataSource;

            try
            {
                if (selectType >= 2 && CommonMethods.mesConfig.isConnected)//dgv有未上传查询结果且cmb_SelectType选择未上传//
                {
                    switch (selectType)
                    {
                        case 2://进站
                            #region 数据判断
                            if (queryProcessListA == null)
                            {
                                new FrmMsgBoxOutWithAck(2, "未查询到需补传数据, 请确认!".Translated(), "警告".Translated()).ShowDialog();
                                break;
                            }
                            else if (queryProcessListA.Count <= 0)
                            {
                                new FrmMsgBoxOutWithAck(2, "未查询到需补传数据, 请确认!".Translated(), "警告".Translated()).ShowDialog();
                                break;
                            }
                            #endregion

                            #region 数据组合/上传
                            // 2、数据组合
                            for (int i = 0; i < queryProcessListA.Count; i++)
                            {
                                barCodes.Add(queryProcessListA[i].BarCode);
                            }
                            // 数据上传
                            var (success, mesage, resType) = await CommonMethods.hbgMes.ManyCellInStationAsync(CommonMethods.mesConfig.ProductInStation, CommonMethods.mesConfig.siteCode, CommonMethods.mesConfig.lineCode,
                                    CommonMethods.mesConfig.equipNum, CommonMethods.mesConfig.MaterialCode, CommonMethods.mesConfig.mesUserName, barCodes);
                            #endregion

                            #region 数据判断/存入数据库
                            //3、数据判断
                            for (int i = 0; i < barCodes.Count; i++)
                            {
                                if (success) //调用接口成功
                                {
                                    //4、补传成功标志位
                                    totalUpResult = true;

                                    mesResType = resType[i];
                                    flag = "1";
                                    switch (mesResType)
                                    {
                                        case MesResType.C:// 警示（MES认为是可以当成良品流下去的）
                                        case MesResType.D:// 条码上传OK
                                            result = "MES OK";
                                            remark = mesage[i];
                                            break;
                                        case MesResType.A:// 停线，设备报警停机
                                        case MesResType.B:// 排出
                                        default:
                                            result = "MES NG";
                                            remark = mesage[i];
                                            break;
                                    }
                                }
                                else
                                {
                                    flag = "2";
                                    result = "MES NG";
                                    remark = mesage[0];
                                }
                                if (!remark.Contains("发生一个或多个错误"))
                                {
                                    try
                                    {
                                        // 更新数据库
                                        UpdateIsUpMES(0, flag, result, remark, barCodes[i]);
                                    }
                                    catch (Exception ex)
                                    {
                                        LogHelper.Instance.WriteError($"补传更新数据库异常,原因:{ex}", "SysErrorLog");
                                    }
                                }
                            }
                            #endregion

                            // 清零
                            queryProcessListA.Clear();

                            if (totalUpResult)
                            {
                                new FrmMsgBoxOutWithAck(1, "查询范围内进站数据补传成功".Translated(), "提示".Translated()).ShowDialog();
                            }
                            else
                            {
                                new FrmMsgBoxOutWithAck(1, $"查询范围内进站数据补传失败".Translated(), "提示".Translated()).ShowDialog();
                            }
                            break;
                        case 3://出站
                            #region 数据判断
                            if (queryProcessListB == null)
                            {
                                new FrmMsgBoxOutWithAck(2, "未查询到需补传数据, 请确认!".Translated(), "警告".Translated()).ShowDialog();
                                break;
                            }
                            else if (queryProcessListB.Count <= 0)
                            {
                                new FrmMsgBoxOutWithAck(2, "未查询到需补传数据, 请确认!".Translated(), "警告".Translated()).ShowDialog();
                                break;
                            }
                            #endregion

                            #region 数据组合/上传
                            #region 单条 ×
                            //for (int i = 0; i < queryProcessListB.Count; i++)
                            //{
                            //    // 数据上传
                            //    var (success1, mesage1, resType1) = await CommonMethods.hbgMes.SingleCellOutStationAsync(CommonMethods.mesConfig.ProductOutStation, CommonMethods.mesConfig.siteCode, CommonMethods.mesConfig.lineCode,
                            //                 CommonMethods.mesConfig.equipNum, CommonMethods.mesConfig.MaterialCode, CommonMethods.mesConfig.ModelName, CommonMethods.mesConfig.mesUserName, queryProcessListB[i], 1, CommonMethods.mesConfig.materialLotCodeLocator);



                            //    #region 数据判断/存入数据库
                            //    //3、数据判断
                            //    if (success1) // 调用接口成功
                            //    {
                            //        //4、补传成功标志位
                            //        totalUpResult = true;

                            //        flag = "1";
                            //        mesResType = resType1;
                            //        info = queryProcessListB[i].Info;
                            //        // 本地判断OK，MES判断OK
                            //        if (queryProcessListB[i].Result.Contains("OK") && mesResType == MesResType.D)
                            //        {
                            //            result = "OK";
                            //            info = "良品".Translated();
                            //        }
                            //        // 本地判断OK，MES判断NG
                            //        else if (queryProcessListB[i].Result.Contains("OK") && mesResType != MesResType.D)
                            //        {
                            //            switch (mesResType)
                            //            {
                            //                case MesResType.A: // 停线，设备报警停机
                            //                    result = "MES NG";
                            //                    remark = $"A,{mesage1}";
                            //                    break;
                            //                case MesResType.B: // MES不良
                            //                    result = "MES NG";
                            //                    remark = $"B,{mesage1}";
                            //                    break;
                            //                case MesResType.C: // 警示
                            //                    result = "OK"; // MES认为是可以当成良品流下去的
                            //                    remark = $"Alarm:{mesage1}";
                            //                    break;
                            //                case MesResType.D: // 条码上传OK
                            //                    result = "OK";
                            //                    remark = $"D,{mesage1}";
                            //                    break;
                            //                default:
                            //                    result = "MES NG";
                            //                    remark = $"{mesage1}";
                            //                    break;
                            //            }
                            //        }
                            //        // 本地判断NG，MES判断OK
                            //        else if (queryProcessListB[i].Result.Contains("NG") && mesResType == MesResType.D)
                            //        {
                            //            result = "NG";
                            //            remark = $"D,{mesage1}";
                            //        }
                            //        // 本地判断NG，MES判断NG
                            //        else if (queryProcessListB[i].Result.Contains("NG") && mesResType != MesResType.D)
                            //        {
                            //            result = "NG";
                            //            remark = $"{mesResType},{mesage1}";
                            //        }
                            //        // 其他情况
                            //        else
                            //        {
                            //            result = "MES NG";
                            //            remark = mesage1;
                            //        }
                            //    }
                            //    else
                            //    {
                            //        flag = "2";
                            //        result = "MES NG";
                            //        remark = mesage1;
                            //    }
                            //    if (!remark.Contains("发生一个或多个错误"))
                            //    {
                            //        try
                            //        {
                            //            // 更新数据库
                            //            UpdateIsUpMES(1, flag, result, remark, queryProcessListB[i].BarCode, info);
                            //        }
                            //        catch (Exception ex)
                            //        {
                            //            LogHelper.Instance.WriteError($"补传更新数据库异常,原因:{ex}", "SysErrorLog");
                            //        }
                            //    }
                            //    #endregion
                            //}
                            #endregion

                            #region 多条
                            List<string> listRemark = GetList<string>(queryProcessListB.Count, "");//备注
                            List<string> listResult = GetList<string>(queryProcessListB.Count, "OK");//结果
                            List<string> listFlag = GetList<string>(queryProcessListB.Count, "");//是否上传标志
                            List<string> listMesMesage = GetList<string>(queryProcessListB.Count, "");//mesMesage
                            List<MesResType> listMesResType = GetMesType(queryProcessListB.Count);//mesType.B

                            var (success1, mesage1, mesResType1) = await CommonMethods.hbgMes.ManyCellOutStationAsync(CommonMethods.mesConfig.ProductOutStation, CommonMethods.mesConfig.siteCode, CommonMethods.mesConfig.lineCode,
                                     CommonMethods.mesConfig.equipNum, CommonMethods.mesConfig.MaterialCode, CommonMethods.mesConfig.ModelName, CommonMethods.mesConfig.mesUserName, queryProcessListB, 1, CommonMethods.mesConfig.materialLotCodeLocator);
                            if (success1)
                            {
                                //补传成功标志位
                                totalUpResult = true;

                                listMesMesage = mesage1;
                                listMesResType = mesResType1;
                                listFlag = GetList<string>(queryProcessListB.Count, "1");
                            }
                            else
                            {
                                listRemark = GetList<string>(queryProcessListB.Count, "");
                                listFlag = GetList<string>(queryProcessListB.Count, "2");
                            }
                            #endregion

                            #region 数据判断/存入数据库
                            for (int i = 0; i < queryProcessListB.Count; i++)
                            {
                                // 本地判断OK，MES判断OK
                                if (queryProcessListB[i].Result.Contains("OK") && listMesResType[i] == MesResType.D)
                                {
                                    listResult[i] = "OK,MES OK";
                                    queryProcessListB[i].Info = "良品".Translated();
                                }
                                // 本地判断OK，MES判断NG
                                else if (queryProcessListB[i].Result.Contains("OK") && listMesResType[i] != MesResType.D)
                                {
                                    switch (listMesResType[i])
                                    {
                                        case MesResType.A: // 停线，设备报警停机
                                            listResult[i] = "OK,MES NG";
                                            listRemark[i] += $"A,{listMesMesage[i]}";
                                            break;
                                        case MesResType.B: // MES不良
                                            listResult[i] = "OK,MES NG";
                                            listRemark[i] += $"B,{listMesMesage[i]}";
                                            break;
                                        case MesResType.C: // 警示
                                            listResult[i] = "OK,MES OK"; // MES认为是可以当成良品流下去的
                                            listRemark[i] += $"Alarm:{listMesMesage[i]}";
                                            break;
                                        case MesResType.D: // 条码上传OK
                                            listResult[i] = "OK,MES OK";
                                            listRemark[i] += $"D,{listMesMesage[i]}";
                                            break;
                                        default:
                                            listResult[i] = "OK,MES NG";
                                            listRemark[i] += $"{listMesMesage[i]}";
                                            break;
                                    }
                                }
                                // 本地判断NG，MES判断OK
                                else if (queryProcessListB[i].Result.Contains("NG") && listMesResType[i] == MesResType.D)
                                {
                                    listResult[i] = "NG,MES OK";
                                    listRemark[i] += $"D,{listMesMesage[i]}";
                                }
                                // 本地判断NG，MES判断NG
                                else if (queryProcessListB[i].Result.Contains("NG") && listMesResType[i] != MesResType.D)
                                {
                                    listResult[i] = "NG,MES NG";
                                    listRemark[i] += $"{listMesResType[i].ToString()},{listMesMesage[i]}";
                                }
                                // 其他情况
                                else
                                {
                                    listResult[i] = "NG,MES NG";
                                    listRemark[i] += listMesMesage[i];
                                }

                                // 数据赋值
                                queryProcessListB[i].Flag = listFlag[i];
                                queryProcessListB[i].Result = listResult[i].TrimStart(',').TrimEnd(',');
                                queryProcessListB[i].Remark = listRemark[i].TrimStart(',').TrimEnd(',');

                                if (!listRemark[i].Contains("发生一个或多个错误"))
                                {
                                    try
                                    {
                                        // 更新数据库
                                        UpdateIsUpMES(1, queryProcessListB[i].Flag, queryProcessListB[i].Result, queryProcessListB[i].Remark, queryProcessListB[i].BarCode, queryProcessListB[i].Info);
                                    }
                                    catch (Exception ex)
                                    {
                                        LogHelper.Instance.WriteError($"补传更新数据库异常,原因:{ex}", "SysErrorLog");
                                    }
                                }
                            }
                            #endregion
                            #endregion

                            // 清零
                            queryProcessListB.Clear();

                            if (totalUpResult)
                            {
                                new FrmMsgBoxOutWithAck(1, "查询范围内出站数据补传成功".Translated(), "提示".Translated()).ShowDialog();
                            }
                            else
                            {
                                new FrmMsgBoxOutWithAck(1, $"查询范围内进站数据补传失败".Translated(), "提示".Translated()).ShowDialog();
                            }
                            break;
                        default:
                            break;
                    }
                }
                else
                {
                    new FrmMsgBoxOutWithAck(2, "未选择未上传查询或MES未在线, 请确认!".Translated(), "警告".Translated()).ShowDialog();
                }
            }
            catch (Exception ex)
            {
                //CommonMethods.AddLog(true, $"电芯数据补传异常,原因:{ex.Message}");
                LogHelper.Instance.WriteError($"电芯数据补传异常,原因:{ex}", "SysErrorLog");
            }
            #endregion
            finally
            {
                this.btn_ReUpMes.Text = "补传".Translated();
                this.btn_ReUpMes.Enabled = true;
            }
        }

        /// <summary>
        /// 更新数据库字段值
        /// </summary>
        /// <param name="barcode"></param>
        private void UpdateIsUpMES(int type, string flag, string result, string remark, string barcode, string info = "")
        {
            switch (type)
            {
                case 0://结果，备注，进站是否上传MES
                    AGearEntity m = new AGearEntity
                    {
                        BarCode = barcode,
                        Flag = flag,
                        Result = result,
                        Remark = remark,
                    };
                    int a = CommonMethods.db.UpdateSingle(m, it => new AGearEntity() { Flag = m.Flag, Result = m.Result, Remark = m.Remark }, it => it.BarCode == m.BarCode);
                    break;
                case 1://结果，备注，出站是否上传MES
                    BGearEntity m1 = new BGearEntity
                    {
                        BarCode = barcode,
                        Flag = flag,
                        Info = info,
                        Result = result,
                        Remark = remark,
                    };
                    int b = CommonMethods.db.UpdateSingle(m1, it => new BGearEntity() { Flag = m1.Flag, Info = m1.Info, Result = m1.Result, Remark = m1.Remark }, it => it.BarCode == m1.BarCode);
                    break;
                default:
                    break;
            }
        }

        #region 创建空的数组List
        public List<T> GetList<T>(int num, T data)
        {
            List<T> list = new List<T>();
            for (int i = 0; i < num; i++)
            {
                list.Add(data);
            }
            return list;

        }

        public List<MesResType> GetMesType(int Num)
        {
            List<MesResType> mesResTypes = new List<MesResType>();
            for (int i = 0; i < Num; i++)
            {
                mesResTypes.Add(MesResType.B);
            }
            return mesResTypes;
        }
        #endregion
        #endregion
    }
}
